package router

import (
	"net/http"
	"xiaoniu-registry/internal"
	"xiaoniu-registry/internal/heartbeat
	"xiaoniu-registry/internal/instance"

	"xiaoniu-registry/internal/metrics"
	
	"xiaoniu-registry/internal/heartbeat"
	"xiaoniu-registry/internal/metrics"
)

// SetupRoutes 设置所有路由
func SetupRoutes() *http.ServeMux {
	mux := http.NewServeMux()

	// 创建中间件链
	middlewareChain := middleware.Chain(
		middleware.Recovery,
		middleware.Logging,
		middleware.CORS,
		middleware.RateLimiting,
	)

	// API路由
	mux.Handle("/api/beat", middlewareChain(http.HandlerFunc(heartbeat.BeatHandler)))
	mux.Handle("/api/service/list", middlewareChain(http.HandlerFunc(service.ListHandler)))
	mux.Handle("/api/instance/list", middlewareChain(http.HandlerFunc(instance.ListHandler)))
	mux.Handle("/api/instance/add", middlewareChain(http.HandlerFunc(instance.AddInstanceHandler)))
	mux.Handle("/api/instance/delete", middlewareChain(http.HandlerFunc(instance.DeleteInstanceHandler)))

	// 添加实例管理API
	mux.Handle("/api/instance/offline", middlewareChain(http.HandlerFunc(instance.OfflineInstanceHandler)))
	mux.Handle("/api/instance/online", middlewareChain(http.HandlerFunc(instance.OnlineInstanceHandler)))

	// Web控制台路由（不需要速率限制）
	webMiddleware := middleware.Chain(
		middleware.Recovery,
		middleware.Logging,
		middleware.CORS,
	)
	mux.Handle("/", webMiddleware(http.HandlerFunc(internal.IndexHandler)))
	mux.Handle("/instance", webMiddleware(http.HandlerFunc(internal.InstanceHtmlHandler)))

	// 静态文件服务
	fileServer := http.FileServer(http.Dir("frontend/"))
	mux.Handle("/frontend/", http.StripPrefix("/frontend/", fileServer))

	// 监控和健康检查端点
	mux.Handle("/health", middlewareChain(http.HandlerFunc(metrics.StatusHandler)))
	mux.Handle("/status", middlewareChain(http.HandlerFunc(metrics.DetailedStatusHandler)))
	mux.Handle("/metrics", middlewareChain(http.HandlerFunc(metrics.MetricsHandler)))

return mux

	return mux
}